<?php
session_start();

require_once '../include/common.inc.php';
switch($act){
    // 获取软件过来的链接，验证token有效存在则注册后登录 Author @liuhuiwu<13750088090@sina.cn>
    // 注意ie浏览器不支持此格式跳转
    // {exit("<script>top.location.reload(true);location.href='./';</script>");}
    case "token":
        $url = $ucurl . '/api/internalUserInfo';
        $access_token = $_REQUEST['token'];
        if (empty($access_token)) {header("location:" . $_SERVER['HOST_NAME'] . "/room");exit;}
        $post_data['access_token']       = $access_token;
        $time=time();
        $post_data['time']      = $time;
        $post_data['sign']      = md5($access_token.$time.'33f6ae6da9125c21');
        $res = request_post($url, $post_data);
        $result = json_decode($res,true);
        if ($result['status'] == false) {header("location:" . $_SERVER['HOST_NAME'] . "/room");exit;}
        $password = '';
        $msg=token_login($result,$password);
        if($msg===true){header("location:" . $_SERVER['HOST_NAME'] . "/room");exit;}
        else{ echo "<script>alert('{$msg}');</script>";}
        break;
    case "login":
        $msg=user_login($username,$password);
        if($msg===true){exit("<script>location.href='./';</script>");}
        else{ echo "<script>alert('{$msg}');</script>";}
        break;
    case "reg":
        if($_SESSION['mcode'] != $mcode)
            exit("<script>alert('验证码错误！');location.href='?'</script>");
        $guestexp = '^Guest|'.$cfg['config']['regban']."Guest";
        if(preg_match("/\s+|{$guestexp}/is", $u))
            exit("<script>alert('用户名禁用！');</script>");

        $query=$db->query("select uid from {$tablepre}members where username='{$u}' limit 1");
        if($db->num_rows($query))exit("<script>alert('用户名已经被使用!换一个，如{$u}1985');location.href='?'</script>");

        $regtime=gdate();
        // 传递password变量 start 20161111 Author @liuhuiwu<13750088090@sina.cn>
        // $p=md5($p);
        $password = $p;
        $p=md5($password);
        // 传递password变量 end 20161111 Author @liuhuiwu<13750088090@sina.cn>
        if(isset($_COOKIE['tg'])) {
            $tuser=userinfo($_COOKIE['tg'],'{username}');
        } else {
            $tuser = rand_kefu();
        }
        if($cfg['config']['regaudit']=='1')$state='0';
        else $state='1';


        // 用户中心注册start20161111 Author @liuhuiwu<13750088090@sina.cn>
        $url = $ucurl . '/oauth/register';
        $data = array(
            'grant_type' => 'register',
            'client_id' => '7',
            'client_secret' => 'o8fFtWOY8bytC3nFGaTVCpWif01Z3viiJpWscIpBua',
            'username' => $u,
            'password' => $password,
            'repassword' => $password,
            'register_type' => 'livePC',
            'phone' => $phone,
            'key' => $_SESSION['mcode'],
        );

        $res = request_post($url, $data);
        $res =json_decode($res,true);

        if(isset($res['status'])&&$res['status'] == 'false'){
            exit("<script>alert('".$res['message']."');history.go(-1);</script>");
        }

        if(isset($res['state'])&&$res['state'] == false){
            exit("<script>alert('".$res['msg']."');history.go(-1);</script>");
        }

        // 用户中心注册end20161111 Author @liuhuiwu<13750088090@sina.cn>

//		$db->query("insert into {$tablepre}members(username,password,sex,email,regdate,regip,lastvisit,lastactivity,gold,realname,gid,phone,fuser,tuser,state)	values('$u','$p','2','$email','$regtime','$onlineip','$regtime','$regtime','0','$qq','1','$phone','$tuser','$tuser','$state')");
        $db->query("insert into {$tablepre}members(username,password,sex,email,regdate,regip,lastvisit,lastactivity,gold,realname,gid,phone,fuser,tuser,state)	values('$u','$p','2','','$regtime','$onlineip','$regtime','$regtime','0','','1','$phone','$tuser','$tuser','$state')");
        $uid=$db->insert_id();
        $db->query("replace into {$tablepre}memberfields (uid,nickname)	values('$uid','$u')	");

        $db->query("insert into  {$tablepre}msgs(rid,ugid,uid,uname,tuid,tname,mtime,ip,msg,type)
	values('{$cfg[config][id]}','1','{$uid}','{$u}','{$cfg[config][defvideo]}','{$cfg[config][defvideonick]}','".gdate()."','{$onlineip}','用户注册','2')
		");

        $msg=user_login($u,$p2);

        if($msg===true){exit("<script>location.href='./';</script>");}
        else{ echo "<script>alert('注册成功！$msg');	</script>";}
        break;
    case "logout":
        unset($_SESSION['login_uid']);
        unset($_SESSION['login_user']);
        session_destroy();
        header("location:index.php");
        break;
}
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title><?=$cfg['config']['title']?> </title>
    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="default">
    <link href="images/minilogin.css" rel="stylesheet" type="text/css"  />
    <script src="script/jquery.min.js"></script>
    <script src="script/layer.js"></script>
</head>
<body>


<img border='0' src='http://gc-download.oss-cn-hangzhou.aliyuncs.com/yzgw/room/images/loginBg-r<?=$rtypeid?>.jpg?t=<?=time()?>' width='100%' height='100%' style='position: absolute; z-index: -1;margin:0px;padding:0px'>

<div class="login">

    <div class="header">
        <div class="switch" id="switch">
            <!--                <a class="switch_btn_focus" id="switch_qlogin" href="javascript:void(0);" tabindex="7">快速登录</a>-->
            <!--			<a class="switch_btn" id="switch_login" href="javascript:void(0);" tabindex="8">快速注册</a>-->
            <!--            <div class="switch_bottom" id="switch_bottom" style="position: absolute; width: 66px; left: 0px;"></div>-->
        </div>
    </div>


    <div class="web_qr_login" id="web_qr_login" style="display: block; height: 235px;">

        <!--登录-->
        <div class="web_login" id="web_login">


            <div class="login-box">


                <div class="login_form">
                    <form action="?act=login" method="post" enctype="application/x-www-form-urlencoded"  name="loginform"  id="login_form" class="loginForm" >
                        <div class="uinArea" id="uinArea">
                            <label class="input-tips" for="username">帐号：</label>
                            <div class="inputOuter" id="uArea">

                                <input type="text" id="username" name="username" class="inputstyle"/>
                            </div>
                        </div>
                        <div class="pwdArea" id="pwdArea">
                            <label class="input-tips" for="password">密码：</label>
                            <div class="inputOuter" id="pArea">

                                <input type="password" id="password" name="password" class="inputstyle"/>
                            </div>
                        </div>

                        <div style="padding-left:60px;margin-top:20px;"><input type="submit" value="登 录" style="width:150px;" class="button_blue"/></div>
                    </form>
                </div>

            </div>

        </div>
        <!--登录end-->
    </div>

    <!--注册-->
    <div class="qlogin" id="qlogin" style="display: none; ">

        <div class="web_login"> <form action="?act=reg" method="post" enctype="application/x-www-form-urlencoded" id="regUser">
                <ul class="reg_form" id="reg-ul">
                    <!-- <div id="userCue" class="cue">快速注册请注意格式</div> -->
                    <li>

                        <label for="user"  class="input-tips2">用户名：</label>
                        <div class="inputOuter2">
                            <input type="text" id="u" name="u" maxlength="16" class="inputstyle2" placeholder="6-16位字符"/>
                        </div>

                    </li>

                    <li>
                        <label for="passwd" class="input-tips2">密码：</label>
                        <div class="inputOuter2">
                            <input type="password" id="p"  name="p" maxlength="16" class="inputstyle2"/>
                        </div>
                    </li>
                    <li>
                        <label for="passwd2" class="input-tips2">确认密码：</label>
                        <div class="inputOuter2">
                            <input type="password" id="p2" name="p2" maxlength="16" class="inputstyle2" />
                        </div>

                    </li>

                    <!--                <li>-->
                    <!--                 <label for="qq" class="input-tips2">QQ：</label>-->
                    <!--                    <div class="inputOuter2">-->
                    <!---->
                    <!--                        <input type="text" id="qq" name="qq" maxlength="12" class="inputstyle2"/>-->
                    <!--                    </div>-->
                    <!---->
                    <!--                </li>-->
                    <!--                <li>-->
                    <!--                 <label for="email" class="input-tips2">邮箱：</label>-->
                    <!--                    <div class="inputOuter2">-->
                    <!---->
                    <!--                        <input type="text" id="email" name="email" maxlength="30" class="inputstyle2"/>-->
                    <!--                    </div>-->
                    <!---->
                    <!--                </li>-->
                    <li>
                        <label for="phone" class="input-tips2">手机：</label>
                        <div class="inputOuter2" style="width: 215px;">
                            <input type="text" id="phone" name="phone" maxlength="11" class="inputstyle2" style="width: 140px;"/>
                            <a href="javascript:void(0);" onclick="sendSMS();" id="sendsms">发送验证码</a>
                            <!--a onclick="sendSMS();" id="sendsms" style="width: 60px; text-align: center; padding: 6px 10px; margin: 2px 0; cursor: pointer; border: 0; background-color: #CCC; display: inline-block;">发送验证码</a>-->
                        </div>

                    </li>
                    <li>
                        <label for="mcode" class="input-tips2">验证码：</label>
                        <div class="inputOuter2">
                            <input type="text" id="mcode" name="mcode" maxlength="11" class="inputstyle2"/>
                        </div>
                    </li>
                    <li>
                        <div class="inputArea">
                            <input type="button" id="reg"  style="margin-top:10px;margin-left:85px;" class="button_blue" value="同意协议并注册"/>
                        </div>

                    </li><div class="cl"></div>
                </ul></form>


        </div>


    </div>
    <!--注册end-->
</div>
<script>
    var ds;
    function sendSMS() {
        var phone = $('input[name="phone"]').val();
        var res = validatemobile(phone);
        if(!res) {
            return;
        }

        // 调用短信第三方接口start 20161112 Author @liuhuiwu<13750088090@sina.cn>
        $.ajax({
            type: "post",
            url: 'sms.php',
            dataType: "json",
            data: {"phone": phone},
            success: function(d) {
                var obj = JSON.parse(d);
                // alert(obj.MsgCode);

                if (obj.MsgCode == '1') {
                    //layer.msg('验证码发送成功', 2, 1);
                    alert('验证码发送成功');
                    ds = setInterval('countdown()', 1000);
                } else if (obj.MsgCode == '-2') {
                    //layer.msg('验证码发送失败', 2, 0);
                    alert('一个手机号只能注册一次');
                } else {
                    alert('验证码发送失败');
                }
            }
        });
        // 调用短信第三方接口end 20161112 Author @liuhuiwu<13750088090@sina.cn>
    }
    function countdown() {
        var times = $('#sendsms').html();
        times = parseInt(times);
        var isint = isNaN(times);
        if(isint) {
            times = 61;
            $('#sendsms').removeAttr('onclick');
        }
        times = times - 1;
        if(times <= -1) {
            clearInterval(ds);
            $('#sendsms').html('发送验证码');
            $('#sendsms').attr('onclick', 'sendSMS()');
        } else {
            $('#sendsms').html(times);
            $('#sendsms').attr('');
        }
    }
    function validatemobile(mobile) {
        if(mobile.length==0) {
            //layer.msg('请输入手机号码', 2, 0);
            alert('请输入手机号码');
            return false;
        }
        if(mobile.length!=11) {
            //layer.msg('请输入有效的手机号码', 2, 0);
            alert('请输入有效的手机号码');
            return false;
        }

        var myreg = /^0?1[3|4|5|8][0-9]\d{8}$/;
        if(!myreg.test(mobile)) {
            //layer.msg('请输入有效的手机号码', 2, 0);
            alert('请输入有效的手机号码');
            return false;
        }
        return true;
    }
    $(function(){

        $('#switch_qlogin').click(function(){
            $('#switch_login').removeClass("switch_btn_focus").addClass('switch_btn');
            $('#switch_qlogin').removeClass("switch_btn").addClass('switch_btn_focus');
            $('#switch_bottom').animate({left:'0px',width:'66px'});
            $('#qlogin').css('display','none');
            $('#web_qr_login').css('display','block');
            try{
                parent.layer.iframeAuto(parent.layer.getFrameIndex(window.name));
            }catch(e){}
        });
        $('#switch_login').click(function(){

            $('#switch_login').removeClass("switch_btn").addClass('switch_btn_focus');
            $('#switch_qlogin').removeClass("switch_btn_focus").addClass('switch_btn');
            $('#switch_bottom').animate({left:'152px',width:'66px'});

            $('#qlogin').css('display','block');
            $('#web_qr_login').css('display','none');
            try{
                parent.layer.iframeAuto(parent.layer.getFrameIndex(window.name));
            }catch(e){}
        });
        if(getParam("a")=='0')
        {
            $('#switch_login').trigger('click');
        }

    });

    function logintab(){
        scrollTo(0);
        $('#switch_qlogin').removeClass("switch_btn_focus").addClass('switch_btn');
        $('#switch_login').removeClass("switch_btn").addClass('switch_btn_focus');
        $('#switch_bottom').animate({left:'152px',width:'66px'});
        $('#qlogin').css('display','none');
        $('#web_qr_login').css('display','block');

    }


    //根据参数名获得该参数 pname等于想要的参数名
    function getParam(pname) {
        var params = location.search.substr(1); // 获取参数 平且去掉？
        var ArrParam = params.split('&');
        if (ArrParam.length == 1) {
            //只有一个参数的情况
            return params.split('=')[1];
        }
        else {
            //多个参数参数的情况
            for (var i = 0; i < ArrParam.length; i++) {
                if (ArrParam[i].split('=')[0] == pname) {
                    return ArrParam[i].split('=')[1];
                }
            }
        }
    }


    var reMethod = "GET",
        pwdmin = 6;

    $(document).ready(function() {


        $('#reg').click(function() {

            if ($('#u').val() == "") {
                $('#u').focus().css({
                    border: "1px solid red",
                    boxShadow: "0 0 2px red"
                });
                $('#userCue').html("<font color='red'><b>×用户名不能为空</b></font>");
                return false;
            }



            if ($('#u').val().length < 2 || $('#u').val().length > 16) {

                $('#u').focus().css({
                    border: "1px solid red",
                    boxShadow: "0 0 2px red"
                });
                $('#userCue').html("<font color='red'><b>×用户名位2-16字符</b></font>");
                return false;

            }

            var phone = $('input[name="phone"]').val();
            var res = validatemobile(phone);
            if(!res) {
                return;
            }

            $.ajax({
                type: reMethod,
                url: '../ajax.php?act=regcheck',
                data: "username=" + $("#u").val() + '&temp=' + new Date(),
                dataType: 'html',
                success: function(result) {

                    if (result!='1') {
                        $('#u').focus().css({
                            border: "1px solid red",
                            boxShadow: "0 0 2px red"
                        });
                        if(result=='-1')
                            $("#userCue").html("<font color='red'><b>×用户名含关键字，不能使用！</b></font>");
                        else if(result=='0')
                            $("#userCue").html("<font color='red'><b>×用户名被占用！</b></font>");
                        return false;
                    } else {
                        $('#u').css({
                            border: "1px solid #D7D7D7",
                            boxShadow: "none"
                        });
                    }

                }
            });


            if ($('#p').val().length < pwdmin) {
                $('#p').focus();
                $('#userCue').html("<font color='red'><b>×密码不能小于" + pwdmin + "位</b></font>");
                return false;
            }
            if ($('#p2').val() != $('#p').val()) {
                $('#p2').focus();
                $('#userCue').html("<font color='red'><b>×两次密码不一致！</b></font>");
                return false;
            }
//		var semail=/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/;
//		if($('#email').val().length < 7 || !semail.test( $('#email').val())){
//			$('#userCue').html("<font color='red'><b>×邮箱格式错误！</b></font>");
//			$('#email').focus().css({
//				border: "1px solid red",
//				boxShadow: "0 0 2px red"
//			});
//			return false;
//		}
//		var sqq = /^[1-9]{1}[0-9]{4,9}$/;
//		if (!sqq.test($('#qq').val()) || $('#qq').val().length < 5 || $('#qq').val().length > 12) {
//			$('#qq').focus().css({
//				border: "1px solid red",
//				boxShadow: "0 0 2px red"
//			});
//			$('#userCue').html("<font color='red'><b>×QQ号码格式不正确</b></font>");
//			return false;
//		} else {
//			$('#qq').css({
//				border: "1px solid #D7D7D7",
//				boxShadow: "none"
//			});
//
//		}

            $('#regUser').submit();
        });


    });
</script>
</body>
</html>
